package main

import (
	"errors"
	"fmt"
	"mime"
	"net/http"
	"net/url"
	"time"

	"git.dev.tencent.com/lwch/torrent"

	"git.dev.tencent.com/lwch/runtime"
)

type tracker struct {
	announce  string
	hash      []byte
	blockSize int
}

func newTracker(announce string, hash []byte, blockSize int) *tracker {
	return &tracker{announce, hash, blockSize}
}

func (t *tracker) request() ([]torrent.Peer, error) {
	params := make(url.Values)
	params.Set("info_hash", string(t.hash))
	params.Set("peer_id", PID)
	params.Set("port", "80") // TODO: listen port
	params.Set("uploaded", "0")
	params.Set("downloaded", "0")
	params.Set("left", fmt.Sprintf("%d", t.blockSize))
	params.Set("event", "started")
	cli := &http.Client{Timeout: 10 * time.Second}
	req, err := http.NewRequest("GET", t.announce+"?"+params.Encode(), nil)
	runtime.Assert(err)
	req.Header.Set("User-Agent", "Bittorrent")
	resp, err := cli.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
	runtime.Assert(err)
	if resp.StatusCode == http.StatusOK && ct != "text/html" {
		var a torrent.Announce
		runtime.Assert(torrent.NewAnnounceDecoder(resp.Body).Decode(&a))
		if len(a.Failure) > 0 {
			return nil, errors.New(a.Failure)
		}
		return a.Peers, nil
	}
	return nil, fmt.Errorf("http_code=%d", resp.StatusCode)
}
